package second;

import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

/**
 * @author: ZhouBert
 * @date: 2020/7/24
 * @description:
 */
@Slf4j
public class MyBeanFactory {
	private static final String PROPERTY_PATH="/applicationContext.properties";

	private static Properties env = new Properties();

	/**
	 * 加载配置文件（key 相当于 Bean name）
	 */
	static {
		try {
			InputStream inputStream = MyBeanFactory.class.getResourceAsStream(PROPERTY_PATH);
			env.load(inputStream);
		} catch (IOException e) {
			log.error(e.getMessage(), e);
		}
	}

	/**
	 * 工厂创建产品
	 * @return
	 */
	public static UserService createUserService(){
		UserService userService=null;
		try {
			String bName =env.getProperty("userService");
			log.info("bName:{}", bName);
			// 使用全限定名
			Class clazz= Class.forName(bName);
			userService=(UserService) clazz.newInstance();
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			e.printStackTrace();
		} catch (InstantiationException e) {
			e.printStackTrace();
		}finally {
			return userService;
		}
	}

	/**
	 * 工厂创建产品（获取 Bean）
	 * 将 properties 中的 key 作为 传参
	 * @param key	~=beans name
	 * @return
	 */
	public static Object getBean(String key){
		Object obj = null;
		try {
			String bName = env.getProperty(key);
			log.info("get binary name:{}", bName);
			Class<?> clazz = Class.forName(bName);
			obj = clazz.newInstance();
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			e.printStackTrace();
		} catch (InstantiationException e) {
			e.printStackTrace();
		}finally {
			return obj;
		}
	}
}
